package com.yc.order.controller;

import com.yc.api.CartApi;
import com.yc.entity.MemberInfo;
import com.yc.entity.OrderInfo;
import com.yc.order.biz.OrderInfoBiz;
import com.yc.order.biz.OrderitemVOBiz;
import com.yc.vo.OrderitemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderInfoController {
    @Autowired
    private OrderInfoBiz orderInfoBiz;

    @Autowired
    private OrderitemVOBiz orderitemVOBiz;

    @Autowired
    private CartApi cartApi;

    @RequestMapping(value = "findBymno", method = RequestMethod.POST)
    public Map<String,Object> findBymno(HttpSession session) {
        MemberInfo memberInfo = (MemberInfo) session.getAttribute("user");
        List<OrderitemVO> OderitemList = null;
        List<OrderitemVO> OderitemLists = new ArrayList<>();
        List<OrderInfo> OrderList=null;
        Map<String, Object> map= new HashMap<>();
        int page =0;
        Object total = null;
        if(memberInfo ==null){
            map.put("OrderList",null);
            map.put("total",0);
            map.put("OderitemList",null);
            return  map;
        }
        String mno = memberInfo.getMno().toString();
        try {
            OrderList = orderInfoBiz.findBymno(mno);
            total = orderInfoBiz.findItemCountByMno(mno).get("total_orderitem");
            OderitemList = orderitemVOBiz.findByOno(OrderList.get(page).getOno());
            for(OrderitemVO vo :OderitemList){
                String pics = vo.getPics();
                String[] pic = pics.split(";");
                vo.setPics(pic[0]);
                OderitemLists.add(vo);
            }
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        map.put("OrderList",OrderList);
        map.put("total",total);
        map.put("OderitemList",OderitemLists);
        return map;
    }

    @RequestMapping(value = "addOrder", method = RequestMethod.POST)
    public Map<String, Object> addOrder(@RequestBody String cnos, HttpSession session) {
        System.out.println(cnos);
        Map<String, Object> map = orderInfoBiz.add(cnos);
        MemberInfo member = (MemberInfo) session.getAttribute("user");
        List<Map<String, Object>> carts = cartApi.findByMno(member.getMno());
        //重新查询购物车中数据，更新session
        session.setAttribute("cartList", carts);
        return map;
    }


}
